﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using WebShop.Models;

namespace WebShop.Controllers
{
    public class OrderController : Controller
    {
        private WGRUSEntities db = new WGRUSEntities();

        //
        // GET: /Order/Create

        public ActionResult Create()
        {
            UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName == User.Identity.Name);

            Order order = new Order
            {
                Customer_Id = user.Customer_Id,
                Delevery_Att = user.UserName,
                Delevery_City = user.Customer.City,
                Delevery_Name = user.Customer.Name,
                Delevery_Street = user.Customer.Street,
                Delevery_Zip = user.Customer.Zip
            };

            return View(order);
        }

        //
        // POST: /Order/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Order order)
        {
            if (ModelState.IsValid)
            {
                UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName == User.Identity.Name);
                order.Customer_Id = user.Customer_Id;
                order.Created = DateTime.Now;
                
                var items = db.Baskets.Where(b => b.Customer_Id == user.Customer_Id);
                foreach (var item in items)
                {
                    var orderLine = new OrderLine
                    {
                        Item_Code = item.Item_Code,
                        Item_Description = item.Item_Description,
                        Item_UnitPrice = item.UnitPrice,
                        Quantity = item.Quantity
                    };
                    order.OrderLines.Add(orderLine);
                    db.Baskets.Remove(item);
                }

                db.Orders.Add(order);
                db.SaveChanges();
                HandleOrder(order, user);
                return RedirectToAction("Thanks");
            }

            return View(order);
        }


        [HttpGet, ActionName("Thanks")]
        public ActionResult Thanks()
        {
            return View();
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// The order must be submitted into the order queue for further processing
        /// </summary>
        /// <param name="order"></param>
        private void HandleOrder(Order order, UserProfile user)
        {
            XDocument xlmOrder;
            xlmOrder = BuildXml(order, user);
            // todo: Endpoint implementation
        }

        private XDocument BuildXml(Order order, UserProfile user)
        {
            var cust = user.Customer;
            var xmlOrder =
                new XDocument(
                    new XElement("Order",
                        new XElement("Customer",
                            new XElement("Id", cust.Phone),
                            new XElement("Name", cust.Name),
                            new XElement("Street", cust.Street),
                            new XElement("Zip", cust.Zip),
                            new XElement("City", cust.City
                                )),
                        new XElement("OrderDetails",
                            new XElement("ByUser", user.UserName),
                            new XElement("Delivery",
                                order.Delevery_Att.ToXElement("Att"),
                                order.Delevery_Name.ToXElement("Name"),
                                order.Delevery_Street.ToXElement("Street"),
                                order.Delevery_Zip.ToXElement("Zip"),
                                order.Delevery_City.ToXElement("City")),
                            order.Cust_Order_Ref.ToXElement("OrderReference"),
                            new XElement("OrderLines",
                                from ol in order.OrderLines
                                select new XElement("OrderLine",
                                    new XElement("ItemCode", ol.Item_Code),
                                    ol.Item_Description.ToXElement("ItemDescription"),
                                    new XElement("ItemUnitPrice", ol.Item_UnitPrice),
                                    new XElement("Quantity", ol.Quantity)
                                    )
                                )
                            )
                        ));

            return xmlOrder;
        }
    }

    public static class MyExtensions
    {
        public static XElement ToXElement(this string content, XName name)
        {
            return content == null ? null : new XElement(name, content);
        }
    }
}